import { useState } from 'react'
import { useRouter } from 'next/router'
import * as React from 'react'
import styles from '../styles/Login.module.scss'
import { Button, Input } from 'antd'
import 'antd/dist/antd.css'
import toast from '../components/Toast'
import * as userService from '../services/user.service'
import Nav from '../components/Nav'

export default function Register() {
  const router = useRouter()
  const [username, setUsername] = useState('')
  const [password, setPassword] = useState('')
  const [password2, setPassword2] = useState('')

  const submit = async () => {
    if (password !== password2) {
      toast('两次密码不一致')
    } else {
      let result = await userService.register(username, password)
      if (result.stat === 'OK') {
        await userService.login(username, password)
        router.push('/')
      } else {
        toast(result.message)
      }
    }
  }

  return (
    <div className={styles.wrap}>
      <div className={styles.logo}>懂乎</div>
      <div className={styles.border}>
        <Nav area={'register'} />
        <Input
          type="text"
          className={styles.input}
          placeholder="用户名"
          value={username}
          autoComplete="off"
          onChange={e => setUsername(e.target.value)}
        />
        <Input
          type="password"
          className={styles.input}
          placeholder="密 码"
          value={password}
          onChange={e => setPassword(e.target.value)}
        />
        <Input
          type="password"
          className={styles.input}
          placeholder="再次输入密码"
          value={password2}
          onChange={e => setPassword2(e.target.value)}
        />
        <Button
          block
          disabled={username === '' || password === ''}
          onClick={submit}
        >
          注 册
        </Button>
      </div>
    </div>
  )
}
